package com.qst.crop.controller;

import com.github.pagehelper.PageInfo;
import com.qst.crop.common.Result;
import com.qst.crop.common.StatusCode;
import com.qst.crop.entity.Cart;
import com.qst.crop.entity.MyCart;
import com.qst.crop.entity.Order;
import com.qst.crop.security.entity.JwtUser;
import com.qst.crop.service.CartService;
import com.qst.crop.service.OrderService;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/cart")
public class CartController {
    @Autowired
    private CartService cartService;

    //TODO
    //网页添加失败，但是postman成功
    @ApiOperation("添加购物车信息")
    @PostMapping("/add/{id}")
    public Result<Integer> add(@PathVariable("id") Integer id) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        JwtUser principal = (JwtUser) authentication.getPrincipal();
        String username = principal.getUsername();
        Cart cart = new Cart();
        cart.setOrderId(id);
        cart.setOwnName(username);
        LocalDateTime now = LocalDateTime.now();
        cart.setCount(1);
        cart.setCreateTime(now);
        cart.setUpdateTime(now);

        Result<Integer> res = null;

        int exit = cartService.isExit(id,username);
        if(exit == 0){
            res = new Result<>(true,StatusCode.OK,"添加成功!",cartService.add(cart));
        }
        else{
            res = new Result<>(true,StatusCode.OK,"购物车已存在该商品!");
        }

        return res;
    }

    @ApiOperation("查询全部信息")
    @GetMapping("/show1")
    public Result<List<Cart>> show(){

        return new Result<>(true, StatusCode.OK,"查询成功",cartService.show());
    }

    @GetMapping("/show")
    public Result<List<MyCart>> show1(){
//        cartService.show();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        JwtUser principal = (JwtUser) authentication.getPrincipal();
        String username = principal.getUsername();
        return new Result<>(true, StatusCode.OK,"查询成功",cartService.show1(username));
    }

    @PutMapping("/update/{shoppingId}/{count}")
    @ApiOperation("更新购物车信息")
    public Result<Integer> update(@PathVariable("shoppingId")Integer shoppingId, @PathVariable("count")Integer count){
        return new Result<>(true,StatusCode.OK,"修改成功!",cartService.update(shoppingId,count));
    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation("按照编号删除购物车信息")
    public Result<Integer> delete(@PathVariable("id") int shopping_id){
        return new Result<>(true,StatusCode.OK,"删除成功!",cartService.delete(shopping_id));
    };
}
